<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\BookModel;

class Book extends Base
{
    // 绘本列表
    public function index()
    {
        if(request()->isAjax()){
            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = ['is_del' => '0','pid' => '0'];
            if (!empty($param['searchText'])) {
                $where['title'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $book = new bookModel();
            $selectResult = $book->getbooksByWhere($where, $offset, $limit,'rank desc');
            foreach($selectResult as $key=>$vo){
                $selectResult[$key]['pic'] = '<img src="' . $vo['pic'] . '" width="40px" height="40px">';
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id']));
                $selectResult[$key]['addtime'] = $vo['addtime'];
                $selectResult[$key]['is_put'] = ($vo['is_put'] == '0')?'下架':'上架';
            }

            $return['total'] = $book->getAllbooks($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
        }

        return $this->fetch();
    }

    // 添加文章
    public function bookadd()
    {
        if(request()->isPost()){
            $param = input('post.');
            unset($param['file']);
            $param['addtime'] = date('Y-m-d H:i:s');
            $book = new bookModel();
            $flag = $book->addbook($param,url('book/index'));

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        return $this->fetch();
    }

    public function bookedit()
    {
        $book = new bookModel();
        if(request()->isPost()){

            $param = input('post.');
            unset($param['file']);
            $flag = $book->editbook($param,['id' => $param['id']],url('book/index'));

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input('param.id');
        $this->assign([
            'book' => $book->getOnebook(['id' => $id],'*')
        ]);
        return $this->fetch();
    }

    public function bookDel()
    {
        $id = input('param.id');
        $book = new bookModel();
        /*是否有子类*/
        $book_son = $book->getOnebook(['pid' => $id,'is_del' => '0']);
        if(!empty($book_son)){
            return json(msg('0','','请先清除绘本内容'));
        }
        $flag = $book->delbook($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    public function bookisput()
    {
        $id = input('param.id');
        $is_put = input('param.is_put');
        $book = new bookModel();
        $flag = $book->book_is_put(['is_put' => $is_put],['id' => $id]);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    // 上传缩略图
    public function uploadimg()
    {
        require_once '../vendor/Bigupload/imgcompress.php';
        if(request()->isAjax()){
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS .'image');
            if($info){
                $src =  '/upload' . '/image/' . date('Ymd') . '/' . $info->getFilename();
                $source =  ROOT_PATH.'/public/upload/image/' . date('Ymd') . '/' . $info->getFilename();  
                $dst_img = ROOT_PATH.'/public/upload/image/' . date('Ymd') . '/thumb_' . $info->getFilename();
                $thumb_src =  '/upload' . '/image/' . date('Ymd') . '/thumb_' . $info->getFilename();   
                $percent = 1;  #原图压缩，不缩放，但体积大大降低  
                $image = (new \imgcompress($source,$percent))->compressImg($dst_img);
                return json(msg(0, ['src' => $thumb_src],''));
            }else{
                // 上传失败获取错误信息
                return json(msg(-1, '', $file->getError()));
            }
        }
    }
    // 音频文件
    public function uploadmusic()
    {
        if(request()->isAjax()){
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload'. DS .'music');
            if($info){
                $src =  '/upload'. '/' .'music' . '/' . date('Ymd') . '/' . $info->getFilename();
                return json(msg(0, ['src' => $src], ''));
            }else{
                // 上传失败获取错误信息
                return json(msg(-1, '', $file->getError()));
            }
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        $book = new bookModel();
        $is_put = $book->getOnefield('is_put',['id' => $id]);
        $return_data = [
            '编辑' => [
                'auth' => 'book/bookedit',
                'href' => url('book/bookedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [
                'auth' => 'book/bookdel',
                'href' => "javascript:bookDel(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ],
            '类别子类' => [
                'auth' => 'book/bookedit',
                'href' => url('book/booksonlist', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => ''
            ],
        ];
        if(!$is_put){
            $return_data['上架'] =  [
                'auth' => 'book/bookedit',
                'href' => "javascript:bookisput(".$id.",1".")",
                'btnStyle' => 'primary',
                'icon' => ''
            ];
        }else{
            $return_data['下架'] =  [
                'auth' => 'book/bookedit',
                'href' => "javascript:bookisput(".$id.",0".")",
                'btnStyle' => 'primary',
                'icon' => ''
            ];
        }
        return $return_data;

    }
     // 绘本列表
    public function booksonlist()
    {
        $pid = input('param.id');
        if(request()->isAjax()){
            $param = input('param.'); 
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = ['is_del' => '0','pid' => $param['pid']];
            if (!empty($param['searchText'])) {
                $where['title'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $book = new bookModel();
            $selectResult = $book->getbooksByWhere($where, $offset, $limit,'rank desc');
            // echo $book->getLastSql();
            // var_dump($selectResult);
            foreach($selectResult as $key=>$vo){
                $selectResult[$key]['pic'] = '<img src="' . $vo['pic'] . '" width="40px" height="40px">';
                $selectResult[$key]['audio'] = '<audio src="'.$vo['audio'].'" controls="controls"> </audio>';
                $selectResult[$key]['operate'] = showOperate($this->makesonButton($vo['id']));
                $selectResult[$key]['addtime'] = $vo['addtime'];
            }

            $return['total'] = $book->getAllbooks($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
    }
        $this->assign('pid',$pid);
        return $this->fetch();
    }
     // 添加文章
    public function booksonadd()
    {
        $pid = input('param.pid');
        if(request()->isPost()){
            $param = input('post.');
            unset($param['file']);
            $param['addtime'] = date('Y-m-d H:i:s');
            $book = new bookModel();
            $flag = $book->addbook($param,url('book/booksonlist',['id' => $param['pid']]));
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $this->assign('pid',$pid);
        return $this->fetch();
    }
    public function booksonedit()
    {
        $book = new bookModel();
        if(request()->isPost()){
            $param = input('post.');
            unset($param['file']);
            //var_dump($param);die;
            $flag = $book->editbook($param,['id' => $param['id']],url('book/booksonlist',['id' => $param['pid']]));
            //echo $book->getLastSql();
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input('param.id');
        $this->assign([
            'book' => $book->getOnebook(['id' => $id],'*')
        ]);
        return $this->fetch();
    }
    public function booksonDel()
    {
        $id = input('param.id');
        $book = new bookModel();
        $flag = $book->delbook($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }
     /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makesonButton($id)
    {
        $book = new bookModel();
        $return_data = [
            '编辑' => [
                'auth' => 'book/bookedit',
                'href' => url('book/booksonedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [
                'auth' => 'book/bookdel',
                'href' => "javascript:bookDel(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ],
        ];
        return $return_data;

    }
}
